import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';

/// @date 2020/08/26  14:00
/// @author 程志强
/// @des

class SocketApiRoute extends StatefulWidget {
  @override
  _SocketApiRouteState createState() => _SocketApiRouteState();
}

class _SocketApiRouteState extends State<SocketApiRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("socket"),
      ),
      body: FutureBuilder(
        future: _request(),
        builder: (content, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return Padding(
              padding: const EdgeInsets.all(10.0),
              child: Text(snapshot.data),
            );
          } else {
            return Text("加载中。。。");
          }
        },
      ),
    );
  }

  Future<String> _request() async {
    // 建立连接
    var socket = await Socket.connect("baidu.com", 80);
    // 根据http协议，发送请求
    socket.writeln("GET / HTTP/1.1");
    socket.writeln("Host:baidu.com");
    socket.writeln("Connection:close");
    socket.writeln();
    //发送
    await socket.flush();
    // 读取返回内容
    String responseRes = await utf8.decoder.bind(socket).join();
    await socket.close();
    return responseRes;
  }
}
